/**
 * Created by hao.cheng on 2017/5/5.
 */
import React, { useState, useEffect, useRef } from 'react';
import { Image, Row, Col, Card, message, Popconfirm, PageHeader, Button, Upload, Pagination } from 'antd';
import { UploadOutlined, SettingOutlined, CopyOutlined, DeleteOutlined } from '@ant-design/icons';
import './index.less'

const { Meta } = Card;
let OSS = require('ali-oss');

const IndexPage = () => {
    let ossClient: any = useRef(Function)
    let [list, setList] = useState([])
    

    useEffect(() => {
        initOss()
        getList()
        // getFileContentsList()
    }, [])

    let initOss = async () => {
        ossClient.current = new OSS({
            // yourRegion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
            region: 'oss-cn-beijing',
            // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
            accessKeyId: 'LTAI5t9c4jqTcBcsnpWErf82',
            accessKeySecret: 'q9vUTDbwQdHFpyH3upEJq1wflQxGbN',
            bucket: 'bluedot-test'
        });
    }

    let getList = async () => {
        let result = await ossClient.current.list();
        let fileList = result.objects;
        for(let key in fileList) {
            let item = fileList[key];
            let catalogueFile = item.name.split('/');
            item.title = catalogueFile[catalogueFile.length - 1]
        }
        let list: any = {}
        let catalogueTempData: any = []
        console.log(fileList)
        for(let key in fileList) {
            let item = fileList[key];
            let catalogueFile = item.name.split('/');
            let fileName = catalogueFile.slice(catalogueFile.length - 1)[0];
            let catalogueNameList = catalogueFile.slice(0, catalogueFile.length - 1);

            if (catalogueNameList.length) {
                let tempData: any = null
                let lastIndex = catalogueNameList.length - 1
                for(let i = lastIndex; i >= 0; i--) {
                    let catalogueCurrent = catalogueNameList[i]
                    if (i === lastIndex) {
                        tempData = {}
                        tempData[catalogueCurrent] = {
                            [item.title]: item
                        }
                    } else {
                        tempData = {
                            [catalogueCurrent]: tempData
                        }
                    }
                }
                console.log(tempData)
                catalogueTempData.push(tempData)
            } else {
                list[fileName] = item
            }
        }

        for (let key in catalogueTempData) {
            let catalogueTempItem = catalogueTempData[key]
        }
        setList(fileList)
    }

    let deleteFile = async (item: any) => {
        console.log(item)
        let result = await ossClient.current.delete(item.name);
        getList()
    }
   
    let imageDom = () => {
        return list.map((item: any, index: number) => {
            
            return (
                <Col sm={20} md={12} lg={8} xl={6} xxl={6} style={{textAlign: 'center', margin: '0 0 20px 0'}} key={index}>
                    <Card
                        style={{width: '90%', margin:'0 auto'}}
                        cover={
                            <img
                                alt="example"
                                src={ item.url }
                            />
                        }
                        actions={[
                            <SettingOutlined key="setting" />,
                            <Popconfirm title="确定删除此文件吗？" okText="确定" cancelText="取消" onConfirm={() => deleteFile(item)}>
                                <DeleteOutlined  />,
                            </Popconfirm>,
                            <CopyOutlined onClick={() => copyText(item)} />,
                        ]}
                    >
                        <Meta
                            title={ item.title }
                            // description={ item.name }
                        />
                    </Card>
                </Col>
            )
        })
    }

    // 文字copy
    let copyText = (item: any) => {
        let textarea = document.createElement('textarea')
        textarea.value = item.url
        textarea.id = 'copyTextarea'
        document.body.append(textarea)
        textarea.select()
        document.execCommand("copy")

        message.info('复制成功！');
        
        setTimeout(() => {
            document.getElementById('copyTextarea')?.remove()
        }, 1000)
    }

    // 指定delimiter参数为正斜线（/），将会列举根目录下的Object的版本信息以及文件夹名称。
    let getFileContentsList = async () => {
        let nextKeyMarker = null;
        let nextVersionMarker = null;
        let versionListing = null;
        do {
            versionListing = await ossClient.current.getBucketVersions({
                keyMarker: nextKeyMarker,
                versionIdMarker: nextVersionMarker,
                delimiter: '/'
            })
            nextKeyMarker = versionListing.NextKeyMarker;
            nextVersionMarker = versionListing.NextVersionIdMarker;
        } while (versionListing.isTruncated);
    }

    const uploadProps = {
        name: 'file',
        action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
        headers: {
          authorization: 'authorization-text',
        },
        onChange(info: any) {
            console.log(info.file)
            let result = ossClient.current.putStream(info.file.name, info.file.originFileObj)
            console.log(result);
            return;
          if (info.file.status !== 'uploading') {
            console.log(info.file, info.fileList);
          }
          if (info.file.status === 'done') {
            message.success(`${info.file.name} file uploaded successfully`);
          } else if (info.file.status === 'error') {
            message.error(`${info.file.name} file upload failed.`);
          }
        },
    };

    return (
        <div className="page">
            <PageHeader
                className="site-page-header"
                onBack={() => null}
                title=""
                subTitle=""
                backIcon={ false }
                extra={[
                    <Upload {...uploadProps} key={0}>
                        <Button icon={<UploadOutlined />}>图片上传</Button>
                    </Upload>
                ]}
                style={{margin: '20px auto'}}
            />
            <Row style={{margin: '20px auto'}}>
                { imageDom() }
            </Row>
            <div className="pagination-view">
                <Pagination defaultCurrent={1} total={50} size="default"></Pagination>
            </div>
        </div>
    )
};

export default IndexPage;